package com.unleashyouradventure.swapi.load.httpclient;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;

public class GZipHandler implements HttpResponseInterceptor, HttpRequestInterceptor {

    private final static String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
    private final static String HEADER_ACCEPT_ENCODING_GZIP = "gzip";

    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        Header[] encodings = request.getHeaders(HEADER_ACCEPT_ENCODING);
        String encoding = (encodings.length > 0) ? encodings[0].getValue() : null;
        encoding = appendValue(encoding, HEADER_ACCEPT_ENCODING_GZIP);
        request.setHeader(HEADER_ACCEPT_ENCODING, encoding);
    }

    public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
        HttpEntity entity = response.getEntity();
        Header ceheader = entity.getContentEncoding();
        if (ceheader != null) {
            HeaderElement[] codecs = ceheader.getElements();
            for (int i = 0; i < codecs.length; i++) {
                if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                    // TODO response.setEntity(new
                    // GzipDecompressingEntity(response.getEntity()));
                    return;
                }
            }
        }
    }

    public String appendValue(String allValues, String valueToAppend) {
        if (allValues == null || allValues.length() == 0) {
            return valueToAppend;
        } else if (allValues.contains(valueToAppend)) {
            return allValues;
        } else
            return valueToAppend + ", " + allValues;
    }
}
